# -*- coding: utf8 -*-

from google.appengine.ext import ndb
from google.appengine.api import memcache


class StatCnt(ndb.Model):
    """ base class for statistic
    cnt_guess: (ndb.IntegerProperty()) total amount of guessed word
    cnt_fail: (ndb.IntegerProperty()) total amount of failed word
    cnt_no_result: (ndb.IntegerProperty()) total amount of words which was\
        not guessed or failed in game
    """

    cnt_guess = ndb.IntegerProperty()
    cnt_fail = ndb.IntegerProperty()
    cnt_no_result = ndb.IntegerProperty()

    default_values = {
        'cnt_fail': 0,
        'cnt_guess': 0,
        'cnt_no_result': 0
    }

    def __init__(self, **kwargs):
        values = dict(self.default_values)
        values.update(kwargs)
        super(StatCnt, self).__init__(**values)


class TTimeToCnt(StatCnt):
    """ Word statistic for one (total time)
    time_sec: (ndb.IntegerProperty()) total time the word was showed
    """

    time_sec = ndb.IntegerProperty()

    def key(self):
        return self.time_sec

    def merge(self, other_hist):
        self.cnt_fail += other_hist.cnt_fail
        self.cnt_guess += other_hist.cnt_guess
        self.cnt_no_result += other_hist.cnt_no_result


class LTimeAttemptNToCnt(StatCnt):
    """ Word statistic for one (last attempt time and num of attempts)
    time_sec: (ndb.IntegerProperty()) time the word was showed in last attempt
    num_attempts: (ndb.IntegerProperty()) total number of attempts
    """

    time_sec = ndb.IntegerProperty()
    num_attempts = ndb.IntegerProperty()

    def key(self):
        return (self.time_sec, self.num_attempts)

    def merge(self, other_hist):
        self.cnt_fail += other_hist.cnt_fail
        self.cnt_guess += other_hist.cnt_guess
        self.cnt_no_result += other_hist.cnt_no_result


class WordStatistic(ndb.Model):
    """ Word statistic
    hist_ltime_nattempt:(StructuredProperty(LTimeAttemptNToCnt, repeated=True))
    (last attempt time, num of attempts) -> (num of words every type)
    hist_ttime: (ndb.StructuredProperty(TTimeToCnt, repeated=True))
    (total time) -> (num of words every type)
    """
    hist_ltime_nattempt = ndb.StructuredProperty(LTimeAttemptNToCnt,
                                                 repeated=True)
    hist_ttime = ndb.StructuredProperty(TTimeToCnt, repeated=True)
    word = ndb.StringProperty()


def histogram_update(histogram, new_element):
    """ add new element to histogram

    Args:
    histogram: (ndb.StructuredProperty(<StatClass>, repeated=True)
    new_element: (<StatClass>) element to put in histogram
    """

    for elem in histogram:
        if elem.key() == new_element.key():
            elem.merge(new_element)
            return
    # it is a new key
    histogram.append(new_element)
